package site.tuluan.sp4j.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import site.tuluan.sp4j.common.exception.BizRunTimeException;

/**
 * JSON工具类
 *
 * @author tuluan
 */
public class JsonUtils {
    private static final Logger log = LoggerFactory.getLogger(JsonUtils.class);
    private static final ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        // 将json中的属性还原到bean时，如果有bean中没有的属性，不报错
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 将json中的空字符串在反序列化时转换为null对象
        objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT,true);
    }

    /**
     * 对象转JSON字符串
     * @param obj Java对象
     * @param <T> 类型
     * @return JSON字符串
     */
    public static <T> String obj2JsonStr(T obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("对象转JSON字符串错误", e);
            throw new BizRunTimeException("JSON字符串转JsonNode对象失败", e);
        }
    }

    /**
     * JSON字符串转对象
     * @param result JSON字符串
     * @return JsonNode对象
     */
    public static JsonNode jsonStr2JsonNode(String result){
        try {
            return objectMapper.readTree(result);
        } catch (JsonProcessingException e) {
            log.error("JSON字符串转JsonNode对象失败", e);
            throw new BizRunTimeException("JSON字符串转JsonNode对象失败", e);
        }
    }
}
